<template>
  <div>
    <Card>
      <div class="p-relative">
        <div @click="refresh" class="p-absolute refresh-btn">
          <Icon size='24' type="md-refresh" />
        </div>
        <div class="flex-box search-area">
          <div class="flex-item search-btn">
            <Button type="warning" @click='create'>添加开课模板</Button>
          </div>


        </div>
      </div>
      <Table :columns="tableOption" :data="data.list" border :no-data-text="loadingText ? loadingText : '暂无数据'" border
        ref="tables" editable search-place="top">

        <template slot-scope="{ row, index }" slot="estate">
            <div class="flex-box flex-center flex-margin">
                <i-switch v-model="row.estate" @on-change="changeEstate($event,row.id)">
                    <span slot="open" >启用</span>
                    <span slot="close">禁用</span>
                </i-switch>

            </div>
        </template>
        <template slot-scope="{ row, index }" slot="action">
          <div class="flex-box flex-center flex-margin">

            <Button type='warning' @click="edit(row, index)" size='small'>编辑</Button>
            <Button type='error' @click="del(row, index)" size='small'>删除</Button>

          </div>
        </template>
      </Table>
      <Page class="foot-page" :current='page.current' :total="page.total" :page-size="page.pageSize" show-total
        show-elevator @on-change="changepage"></Page>

    </Card>

    <!-- 添加弹窗 -->
    <Modal v-model="createModal" :title="createTitle" width='700'>
      <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="100">

        <FormItem label="名称" prop="name">
          <Input v-model="formValidate.name" placeholder="请输入模板名称" ></Input>
        </FormItem>

        <FormItem label="开课时间设置" >

            <Button type="warning" @click="setDayModel" >设置模板</Button>
        </FormItem>


        <FormItem label="是否开启">
          <RadioGroup v-model="formValidate.estate">
            <Radio label="1">启用</Radio>&nbsp;&nbsp;&nbsp;&nbsp;
            <Radio label="2">禁用</Radio>&nbsp;&nbsp;&nbsp;&nbsp;
          </RadioGroup>
        </FormItem>

      </Form>
      <div slot="footer">
        <Button type="warning" @click="save('formValidate')" :disabled="isDisable" :loading="isLoading">保存</Button>
      </div>
    </Modal>



    <!-- 删除弹窗 -->
    <Modal v-model="delModal" title="提示" width="250">
      <p class="font16">
        <Icon class='del-tips-icon' type="ios-alert-outline" color='orange' size='22' />确定删除该数据吗？
      </p>
      <div slot="footer">
        <Button @click='delModal=false'>取消</Button>
        <Button type="primary" @click='confirmDel'>确定</Button>
      </div>
    </Modal>

     <!-- 价格模板 -->
    <Modal v-model="weekPriceModal" title="开课模板" width='1200'>

        <Tabs  :value="tabsName">
           <!-- <TabPane :label="item.name" :name="'ball_property_'+item.id" v-for="(item,index) in checkboxPropert"> -->
          <TabPane label="开课模板" :name="tabsName" >

              <div class="fee-box" style="width: 98%;">
                <div class="fee-head"> <span>批量设置</span>
                  <Button type="warning" class="fee-add" size="small" @click='batchInsert'>新增</Button>
                  <Button type="info" class="fee-batch" size="small" @click='batchSet'>批量设置</Button>
                </div>
                <div style="padding:5px 15px  ">
                  <Row :gutter="16" v-for="(item,index) in batchLen">
                    <Col span="5">
                    <TimePicker type="timerange"    :disabled-hours="[0,1,2,3,4,5,6,7]" hide-disabled-options format="HH:mm"
                      @on-change="batchAddTime($event,index)" placeholder="请选择时间段" style="width: 100%"> </TimePicker>
                    </Col>
                    <Col span="5">
                    <Input @on-keyup="batchAddAmount($event,index)"   type="number" placeholder="请设置价格"> <span
                      slot="append">元</span></Input>

                    </Col>
                    <Col span="5">
                    <Input @on-keyup="batchAddNum($event,index)"   type="number" placeholder="请设置消费小时"> <span
                      slot="append">时</span></Input>

                    </Col>

                  </Row>
                </div>
              </div>

              <!-- 一周价格表格 -->
              <div class="flex-box flex-fee" style="overflow-y: auto; height: 600px;" >
                <div class="fee-box" v-for="(item,index) in weekArr">
                  <div class="fee-head"> <span>{{item.name}}</span>
                    <!-- <Button type="warning" class="fee-add" size="small" @click='weekInsert(item,index)'>新增</Button> -->
                  </div>
                  <div style="padding:5px 15px  ">

                    <Row :gutter="16" v-if="item.time_range.length>0" v-for="(row,j) in item.time_range">
                      <Col span="8">
                      <TimePicker type="timerange" :disabled-hours="[0,1,2,3,4,5,6,7]" hide-disabled-options format="HH:mm"
                        @on-change="weekAddTime($event,item,index,j)" v-if="item.time_range.length==0" placeholder="请选择时间段"
                        style="width: 100%">
                      </TimePicker>
                      <TimePicker type="timerange" :disabled-hours="[0,1,2,3,4,5,6,7]" hide-disabled-options format="HH:mm"
                        @on-change="weekAddTime($event,item,index,j)" v-if="item.time_range.length>0" :value="row.time"
                        placeholder="请选择时间段" style="width: 100%">
                      </TimePicker>

                      </Col>
                      <Col span="8">
                        <Input @on-keyup="weekAddAmount($event,item,index,j)" v-if="item.time_range.length==0" type="number"
                        placeholder="请设置价格"> <span slot="append">元</span></Input>
                        <Input @on-keyup="weekAddAmount($event,item,index,j)" v-if="item.time_range.length>0" :value="row.price"
                        type="number" placeholder="请设置价格"> <span slot="append">元</span></Input>

                      </Col>
                      <Col span="8">

                        <Input @on-keyup="weekAddNum($event,item,index,j)" v :value="row.num"
                        type="number" placeholder="请设置价格"> <span slot="append">元</span></Input>
                      </Col>

                    </Row>
                  </div>
                </div>
              </div>

           </TabPane>
        </Tabs>

    </Modal>


  </div>
</template>
<!-- 公共弹框，成功，失败，报错，loading -->
<script>
  import {
    mapState,
    mapMutations
  } from 'vuex'
  import {
    permission
  } from '@/config/permission.js'

  // 接口
  import {
    getList,
    add,
    put,
    del,
    setEstate

  } from '@/api/product-group/course-model'
  import {
    tableOption
  } from '../../../data/product-group/course-model.js'
  import Tables from '_c/tables'

  export default {
    name: 'tables_page',
    components: {
      Tables
    },
    created() {
      let _this =this
      this.$nextTick(function() {
        // 权限校验
        _this.role_add = permission(this.roles, 'courseManage/addModel')
        _this.role_edit = permission(this.roles, 'courseManage/editModel')
        _this.role_del = permission(this.roles, 'courseManage/deleteModel')

      })
      this.getList()
    },
    watch: {

    },
    mounted() {

    },
    computed: {
      ...mapState({

        roles: state => state.user.roles

      }),
    },
    data() {
      return {
        // 权限标识
        role_add: false,
        role_edit: false,
        role_del: false,
        // 上传
        tableOption: tableOption,
        delId: '',
        data: {
          list: [],
          stores:[],
          propertys:[],
        },
        createTitle: ' ',
        isAdd: true, // 新增true,修改false
        isDisable: false, // 新增时提交按钮点击状态
        isLoading: false, // 新增时提交按钮loading状态
        weekPriceModal:false,
        loadingText: '',
        batchLen: 1,
        tabsName:'card_model',
        weekArr: [],
        batchTime:[],
        batchAmount:[],
        batchNum:[],
        weekObj:[],
        // 查询参数
        searchObj: {
          name: ''

        },
        // 分页
        page: {
          pageSize: 8,
          current: 1,
          total: 0
        },

        // 分页end
        // 弹窗状态
        createModal: false, // 新增，修改弹窗
        delModal: false, // 删除弹窗

        formValidate: {
          name: '',
          estate:1,
          count: 0,
          amount: 0,
          price: 0,
          store_id:0
        },

        ruleValidate: {
          name: [{
            required: true,
            message: '请输入运动卡名称',
            trigger: 'blur'
          }],
          // price: [{
          //   required: true,
          //   message: '请输入面额',
          //   trigger: 'blur'
          // }],
          // store_id: [{
          //   required: true,
          //   message: '请输入实际售价',
          //   trigger: 'blur'
          // }],
          // ball_property_id: [{
          //   required: true,
          //   message: '请输入会员赠送金额',
          //   trigger: 'blur'
          // }]
        }
      }
    },
    methods: {
      // 列表数据
      getList() {
        let _this = this
        let params = {
          page: this.page.current,
          size: this.page.size,
          name: this.searchObj.name
        }

        getList(params).then(res => {
          if (res.data.status == 1) {
            let result = res.data.data
            _this.data.list = result.list
            _this.page.total = result.total
            _this.page.pageSize = result.size
            _this.data.stores = result.stores
            _this.data.propertys = result.propertys
          } else {
            let config = {
              content: res.data.message,
              background: true
            }
            _this.$Message.error(config)
          }
        }).catch(function(error) {
          // 异常
          console.log(error)
        })
      },

      detail(row) {
        this.detailModal = true;
        this.formValidate = JSON.parse(JSON.stringify(row))

        this.getMakeData();
      },

      changepage(e) {
        this.page.current = e
        this.getList()
      },


      // 新增
      create() {
        // if (!this.role_add) {
        //   let config = {
        //     content: '您没有操作权限',
        //     background: true
        //   }
        //   this.$Message.error(config)
        //   return
        // }
        this.createModal = true
        this.isDisable = false
        this.isLoading =false
        this.createTitle = '添加开课模板'
        this.isAdd = true
        this.formValidate = {} // 表单重置
        this.formValidate.estate = '1';
        // this.batchTime = [];
          //清空初始化数据
        this.weekArr = this.returnWeekArr();

        this.handleReset('formValidate') // 验证重置
      },
      // 修改
      edit(row) {
        // if (!this.role_edit) {
        //   let config = {
        //     content: '您没有操作权限',
        //     background: true
        //   }
        //   this.$Message.error(config)
        //   return
        // }
        this.isDisable = false
        this.isLoading =false
        this.createModal = true
        this.createTitle = '修改开课模板'
        this.isAdd = false
        this.formValidate = {} // 表单重置
        this.formValidate = JSON.parse(JSON.stringify(row))
         this.weekArr = this.returnWeekArr();
        // console.log(row)
        this.formValidate.estate = this.formValidate.estate.toString();

        this.weekObj =this.weekArr = row.weekObj;

        // console.log('********',this.weekObj)
        this.handleReset('formValidate') // 验证重置
      },

      // 删除
      del(row) {
        if (!this.role_del) {
          let config = {
            content: '您没有操作权限',
            background: true
          }
          this.$Message.error(config)
          return
        }
        this.delId = row.id
        this.delModal = true
        // 删除接口
      },
      confirmDel() {
        let _this = this
        let obj = {
          id: this.delId
        }
        del(obj).then(res => {
          if (res.data.status == 1) {

            _this.delModal = false
            _this.$Message.success('操作成功')
            _this.getList() // 重新刷新数据
          } else {
            _this.delModal = false

          }
        }).catch(function(error) {
          // 异常
          _this.delModal = false
          console.log(error)
        })
      },
      // 刷新
      refresh() {
        this.searchObj = {} // 清空搜索框
        this.getList()
      },
      // 重置
      reset() {
        this.searchObj = {} // 清空搜索框
        this.getList()
      },
      // 查询
      search() {
        this.getList()
      },

      save(name) {

        let _this = this
        _this.isDisable = true
        _this.isLoading =true

        this.$refs[name].validate((valid) => {

          if (valid) {

            if (_this.isAdd) {
              // console.log(33)
              // 新增
              let obj = {
                name: _this.formValidate.name,
                weekObj: _this.weekObj,
                store_id: _this.formValidate.store_id,
                estate: _this.formValidate.estate,
                ball_property_id:_this.formValidate.ball_property_id,

              }

              // 新增接口
              add(obj).then(res => {
                _this.isDisable = false
                _this.isLoading =false

                if (res.data.status == 1) {

                  _this.createModal = false
                  _this.getList() // 重新刷新数据
                  _this.$Message.success('操作成功')
                } else {
                  _this.createModal = false
                  // axios响应拦截
                }
              }).catch(function(error) {
                // 异常
                _this.createModal = false
                console.log(error)
              })
            } else {
              // 修改

              let obj = {
                id:_this.formValidate.id,
                 name: _this.formValidate.name,
                 weekObj: _this.weekObj,
                store_id: _this.formValidate.store_id,
                estate: _this.formValidate.estate,
                ball_property_id:_this.formValidate.ball_property_id,
              }

              // 修改接口
              put(obj).then(res => {
                 _this.isDisable = false
                _this.isLoading =false
                if (res.data.status == 1) {

                  _this.createModal = false
                  _this.getList() // 重新刷新数据
                  _this.$Message.success('操作成功')
                } else {

                }
              }).catch(function(error) {
                // 异常
                console.log(error)
              })
            }

          } else {
            this.$Message.error('请输入必填项!')
          }
        })
      },
      changeEstate(e,id){
        let _this = this
        let estate = e?1:2;
        let obj = {
            id:id,
            estate:estate,
        }
        // 修改接口
          setEstate(obj).then(res => {

            if (res.data.status == 1) {


              _this.getList() // 重新刷新数据
              _this.$Message.success('操作成功')
            } else {

            }
          }).catch(function(error) {
            // 异常
            console.log(error)
          })

      },
      handleReset(name) {
        this.$refs[name].resetFields()
      },
      // 批量设置 star
       returnWeekArr() {
        let tempWeekArr = [{
            name: '周一',
            week: 1,
            time_range: [],

          },
          {
            name: '周二',
            week: 2,
            time_range: [],

          },
          {
            name: '周三',
            week: 3,
            time_range: [],

          },
          {
            name: '周四',
            week: 4,
            time_range: [],

          },
          {
            name: '周五',
            week: 5,
            time_range: [],

          },
          {
            name: '周六',
            week: 6,
            time_range: [],

          },
          {
            name: '周日',
            week: 7,
            time_range: [],

          },

        ];

        return tempWeekArr;
      },
      batchAddTime(e, i) {

        this.batchTime[i] = e
        console.log(e)
        console.log(i)

      },
      batchAddAmount(e, i) {

        this.batchAmount[i] = e.target.value
      },
      batchAddNum(e,i){
        this.batchNum[i] = e.target.value
      },
       batchInsert() {
        this.batchLen++;
      },
      weekAddTime(e, item, i, j,m) {
       //半全场 半场特殊处理
       if(m!=undefined){
          item.time_range[j][m].time = e
       }else{
          item.time_range[j].time = e
       }
        this.weekArr[i] = item;
        this.weekObj = this.weekArr;
      },
      weekAddAmount(e, item, i, j,m) {
       if(m!=undefined){
          item.time_range[j][m].price = e.target.value
       }else{
         item.time_range[j].price = e.target.value
       }
        this.weekArr[i] = item;
        this.weekObj = this.weekArr;
      },
      weekAddNum(e, item, i, j,m) {
       if(m!=undefined){
          item.time_range[j][m].num = e.target.value
       }else{
         item.time_range[j].num = e.target.value
       }
        this.weekArr[i] = item;
        this.weekObj = this.weekArr;
      },

      hoverTab() {
        // this.batchLen = 1;
        // this.batchTime = [];
        // this.batchAmount = [];

        // if(this.weekObj[name]!=undefined){
        //   this.weekArr = this.weekObj[name];
        // }else{
        //   this.weekArr = this.returnWeekArr();
        // }

      },
      //批量设置
      batchSet() {


          this.weekArr = this.returnWeekArr();//解决重复数据处理
          // console.log( this.batchTime)
          for (var i in this.weekArr) {

            this.batchTime.forEach((value, j) => {
              let data = {
                time: value,
                price: this.batchAmount[j],
                num:this.batchNum[j]
              }
              //   let data1 = [];
              // this.checkboxVeneuModel.forEach((ve,je)=>{
              //   let data2 =   {
              //          time:value,
              //          price:this.batchAmount[j],
              //          veneu_model:ve
              //       }
              //     data1.push(data2);

              //   })

              if (this.weekArr[i] != undefined) {

                this.weekArr[i].time_range.push(data);
              }

            })
          }


        this.weekObj = this.weekArr
        console.log(434343,this.weekObj)

      },
      setDayModel(){
        this.weekPriceModal =true
      },


      // 批量设置价格

    }

  }
</script>

<style lang="scss">
  @import "./index";
</style>
